package com.shuaiche.yeguan.ui.upload;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.shuaiche.yeguan.LoadingActivity;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.model.BaseResponseModel;
import com.shuaiche.yeguan.model.SCAccessAuthResponse;
import com.shuaiche.yeguan.model.SCCarPicsModel;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.oss.MultiImagesUploadManager;
import com.shuaiche.yeguan.ui.login.SCLoginWrapHelper;
import com.shuaiche.yeguan.util.SPUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.views.dialog.LoadingDialog;
import com.shuaiche.yeguan.views.dialog.PermissionDialog;
import com.shuaiche.yeguan.views.dialog.PrivacyDialog;
import com.shuaiche.yeguan.views.photopicker.ImageCaptureManager;
import com.shuaiche.yeguan.views.photopicker.PhotoPickerActivity;
import com.shuaiche.yeguan.views.photopicker.SelectModel;
import com.shuaiche.yeguan.views.photopicker.intent.PhotoPickerIntent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class CarPictureFragment extends Fragment implements CarPictureAdapter.OnItemClickListener{

    private static final String ARG_PARAM1 = "picList";
    private static final String ARG_PARAM2 = "param2";
    private static final int maxTotal = 16;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private RecyclerView rvCarPictures;
    private CarPictureAdapter adapter;
    private List<String> pictureList = new ArrayList<>();

    /**
     * 需上传的图片
     */
    private ArrayList<String> picList = new ArrayList<>();
    private ItemTouchHelper itemTouchHelper;
    private ActivityResultLauncher<Intent> photoResultLauncher;

    private LoadingDialog loadingDialog;

    public CarPictureFragment() {
        // Required empty public constructor
    }

    public static CarPictureFragment newInstance(ArrayList<String> picList) {
        CarPictureFragment fragment = new CarPictureFragment();
        Bundle args = new Bundle();
        args.putStringArrayList("picList",picList);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ArrayList<String> picList = getArguments().getStringArrayList("picList");
            if (picList != null && !picList.isEmpty()){
                if (picList.size() == 16){
                    pictureList.addAll(picList);
                }else {
                    pictureList.addAll(picList);
                    pictureList.add(CarPictureAdapter.ADD_PIC);
                }
            }else {
                pictureList.add(CarPictureAdapter.ADD_PIC);
            }
        }

        photoResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK){
                            handlePhotoActivityResultData(result);
                        }
                    }
                });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_car_picture, container, false);

        initViews(view);
        return view;
    }

    private void initViews(View view) {
        rvCarPictures = view.findViewById(R.id.rv_car_pictures);
        loadingDialog = new LoadingDialog(getContext());

        initRecyclerView();
    }

    private void initRecyclerView() {

//        pictureList.add(CarPictureAdapter.ADD_PIC);

        adapter = new CarPictureAdapter(getContext(),pictureList);
        adapter.setOnItemClickListener(this);

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        rvCarPictures.setLayoutManager(layoutManager);
        rvCarPictures.setAdapter(adapter);

        ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                        ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                return makeMovementFlags(dragFlags, 0);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView,
                                  @NonNull RecyclerView.ViewHolder viewHolder,
                                  @NonNull RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                adapter.swapItems(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                // 不实现滑动删除
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }
        };

        itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(rvCarPictures);
    }

    @Override
    public void onDeleteClick(int position) {
        adapter.removeItem(position);
    }

    @Override
    public void onItemClick(int position) {
        if (CarPictureAdapter.ADD_PIC.equals(pictureList.get(position))){
            checkWriteReadPermission();
        }else {
            //预览图片

        }
    }


    private void checkWriteReadPermission(){

        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            PermissionDialog dialog = new PermissionDialog(getContext(),"申请文件读写权限","获取文件读写权限，读取手机中的图片文件，供您选择上传图片");
            dialog.setOnPermissionResultListener(new PermissionDialog.OnPermissionResultListener() {
                @Override
                public void onConfirm() {
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 10086);
                }

                @Override
                public void onRefuse() {

                }
            });
            dialog.setCancelable(false);
            dialog.show();
        }else {
            PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
            int canUpNum = maxTotal - (pictureList.size()-1);
            Log.e("canUpNum",canUpNum+"");
            intent.setMaxTotal(canUpNum);
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true);
            photoResultLauncher.launch(intent);
        }

    }

    public void addPicture(String picturePath) {
        pictureList.add(picturePath);
        adapter.notifyItemInserted(pictureList.size() - 1);
    }

    private void handlePhotoActivityResultData(ActivityResult result) {
        Intent data = result.getData();
        ArrayList<String> imagePaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);

        if (imagePaths != null && imagePaths.size() > 0) {
            picList = imagePaths;
            loadingDialog.show();
            getOssAuth();
        }
    }

    private void getOssAuth(){
        HttpHelper.getInstance().appendUrl(HttpUrl.OSS_AUTH)
                .get(new HttpCallBack<SCAccessAuthResponse>(getActivity()) {
                    @Override
                    public void onSuccessed(SCAccessAuthResponse result) {
                        SCAccessAuthResponse response = result.getData();
                        uploadPics(response);
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {
                        loadingDialog.dismiss();
                    }
                });
    }

    private void uploadPics(SCAccessAuthResponse auth){
        MultiImagesUploadManager.MultiImagesUploadCallback callback =
                new MultiImagesUploadManager.MultiImagesUploadCallback() {
                    @Override
                    public void onSuccess(List<PutObjectRequest> requests) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        if (requests != null) {
                            pictureList.remove(pictureList.size() -1);

                            for (PutObjectRequest putObjectRequest: requests) {
                                Log.e("uploadResult",SCAppConfig.IMG_URL + putObjectRequest.getObjectKey());
                                pictureList.add("/"+ putObjectRequest.getObjectKey());
                            }

                            if (pictureList.size() < 16){
                                pictureList.add(CarPictureAdapter.ADD_PIC);
                            }

                            if (adapter != null){
                                adapter.notifyDataSetChanged();
                            }
                        }

                    }

                    @Override
                    public void onFailure(List<PutObjectRequest> requests) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        ToastShowUtils.showFailedToast("图片上传失败");
                    }
                };

        new MultiImagesUploadManager().startUpload(picList, callback,
                auth.getAccessKeyId(), auth.getAccessKeySecret(), auth.getSecurityToken(),
                SCAppConfig.OSS_CAR);
    }

    public List<SCCarPicsModel> getCarPictures() {

        List<SCCarPicsModel> uploadList = new ArrayList<>();
        for (String carPic : pictureList) {
            if (!CarPictureAdapter.ADD_PIC.equals(carPic)){
                SCCarPicsModel carPicsModel = new SCCarPicsModel();
                carPicsModel.setTitle(SCAppConfig.CAR_PIC);
                String carPicUrl = carPic;
                carPicsModel.setPicUrl(carPicUrl);
                uploadList.add(carPicsModel);
            }
        }

        return uploadList;
    }

}